package com.tgpms.web.hongbo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.interfaces.dto.HongBoInterface;
import com.tgpms.web.hongbo.dao.WorkProjectMapper;
import com.tgpms.web.hongbo.entity.WorkProject;
import com.tgpms.web.hongbo.service.WorkProjectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created By Riven on 2020-9-15
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class WorkProjectServiceImpl implements WorkProjectService {

    @Resource
    private HongBoInterface hongBoInterface;

    @Resource
    private WorkProjectMapper workProjectMapper;

    @Override
    public int syncWorkProject() throws UnsupportedEncodingException {
        int returnInt;
        List<WorkProject> list = new ArrayList<>();
        int ifEmpty = workProjectMapper.deleteWorkProject();
        if (ifEmpty != -1) {
            Result workProjectResult = hongBoInterface.getWorkProject(-1, -1);
            if (workProjectResult.getSuccess()) {
                String resData = workProjectResult.getData().toString();
                JSONObject resJson = JSONObject.parseObject(resData);
                JSONArray tables = (JSONArray) resJson.get("tables");
                for (Object table : tables) {
                    JSONObject jsonObject = JSONObject.parseObject(table.toString());
                    WorkProject temp = transform(jsonObject);
                    list.add(temp);
                }
            }
        }
        returnInt = workProjectMapper.batchInsert(list);
        return returnInt;
    }

    private WorkProject transform(JSONObject jsonObject) {
        WorkProject temp = new WorkProject();
        temp.setId(jsonObject.get("ID").toString());
        temp.setProCap(jsonObject.get("ProCap").toString());
        temp.setProCode(jsonObject.get("ProCode").toString());
        temp.setInsertUser("TGPMS");
        temp.setInsertDate(new Date());
        temp.setRowstamp(jsonObject.get("ID").toString());
        return temp;
    }
}
